package app

import (
	goredislib "github.com/go-redis/redis/v8"
	"github.com/go-redsync/redsync/v4"
	"github.com/go-redsync/redsync/v4/redis"
	"github.com/go-redsync/redsync/v4/redis/goredis/v8"
	"strconv"
)

var RedisLockerHandel *redsync.Redsync

// 获取锁链接
func RedisLocker() *redsync.Redsync {
	if RedisLockerHandel != nil {
		return RedisLockerHandel
	}

	RedisLockerHandel = InitRedisLocker()
	return RedisLockerHandel
}

// 初始化
func InitRedisLocker() *redsync.Redsync {

	redisConfig, errRedisConfig := Config.GetRedisLockerConfig()
	if errRedisConfig != nil {
		panic(errRedisConfig.Error())
	}

	pools := make([]redis.Pool, 0)
	for _, item := range redisConfig {
		serverStr := item.RedisHost + ":" + strconv.FormatInt(item.RedisPort, 10)

		// 连接
		client := goredislib.NewClient(&goredislib.Options{
			Addr: serverStr,
		})

		pool := goredis.NewPool(client)
		pools = append(pools, pool.(redis.Pool))
	}

	return redsync.New(pools...)
}
